package com.j1ay.forum.filter;

import com.j1ay.forum.handler.LoginFailureHandler;
import com.j1ay.forum.handler.ValidateCodeException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

/**
 * @Author J1ay
 * @Date 2021/12/26 20:07
 * @Description
 */
@Slf4j
@Component
public class VerifyCodeFilter extends OncePerRequestFilter {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;


    @Autowired
    private LoginFailureHandler loginFailureHandler;

    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
        if(StringUtils.equals("/api/user/login", httpServletRequest.getRequestURI())
                && StringUtils.equalsIgnoreCase(httpServletRequest.getMethod(), "post")) {
            try {
                // 1. 进行验证码的校验
                String code = httpServletRequest.getParameter("code").toLowerCase();
                String uuid = httpServletRequest.getParameter("uuid");
                log.info("code==============" + code);
                log.info(uuid);
                String realCode = redisTemplate.opsForValue().get(uuid);
                log.info("realcode===========" + realCode);

               if (Objects.isNull(code)) {
                   throw new ValidateCodeException("验证码不存在~");
               }

               if (StringUtils.isBlank(realCode)) {
                   throw new ValidateCodeException("验证码已过期，请刷新重新获取~");
               }
               if (!(code).equals(realCode.toLowerCase())) {
                   throw new ValidateCodeException("验证码不正确~");
               }
            } catch (ValidateCodeException e) {
                log.info(e.getMessage());
                // 2. 如果校验不通过，调用SpringSecurity的校验失败处理器
                loginFailureHandler.onAuthenticationFailure(httpServletRequest, httpServletResponse, e);
                return ;
            }
        }

        filterChain.doFilter(httpServletRequest, httpServletResponse);
    }
}
